<template>
  <view>
    <van-field
      is-link
      :readonly="true"
      v-show="!props.hidden"
      :label="props.formItem?.title"
      :required="required"
      :rules="rules"
      :input-align="FieldInputAlign.DEFAULT"
      @click="showPicker = true"
    >
      <template #right-icon>
        <view v-if="!isEmpty(_value)">
          <van-tag
            type="primary"
            class="margin-right-xs"
            v-for="(item, index) in _value"
            :key="index"
          >
            {{ item.name }}
          </van-tag>
        </view>
        <view class="ph" v-else>{{ props.placeholder }}</view>
      </template>
    </van-field>
    <van-popup v-model:show="showPicker" round position="bottom" :style="{ height: '80%' }">
      <view class="user-data-container">
        <view class="card">
          <view class="nav-container">
            <span
              class="nav-name"
              v-for="(navItem, index) in navData"
              :key="index"
              @click="pop(navItem, index)"
              ><span class="interval" v-if="index !== 0">|</span>{{ navItem.name }}</span
            >
          </view>
        </view>
        <view class="card">
          <van-cell
            :title="deptItem.name"
            size="large"
            v-for="(deptItem, index) in deptData"
            :key="index"
          >
            <template #right-icon>
              <view class="cell-icon" @click="nextGrade(deptItem)">
                <van-icon name="list-switch" class="suffix-icon" />
                <span class="suffix-text">下级</span>
              </view>
            </template>
          </van-cell>
        </view>

        <!-- 多选人员 -->
        <view class="card">
          <van-checkbox-group v-model="_id_value">
            <van-cell
              :title="userItem.name"
              size="large"
              v-for="(userItem, index) in userData"
              :key="index"
            >
              <template #right-icon>
                <view class="cell-icon">
                  <van-checkbox :name="userItem.id" @click="clickItem(userItem)" />
                </view>
              </template>
            </van-cell>
          </van-checkbox-group>
          <van-empty description="暂无人员" v-if="userData.length < 1" />
        </view>
      </view>

      <van-submit-bar
        :placeholder="true"
        button-color="#1989fa"
        button-text="确定选择"
        @submit="onConfirm"
      />
    </van-popup>
  </view>
</template>
<script setup lang="ts">
  import { isEmpty, isNotBlank } from '@/utils/is';
  import { ref, computed, watch } from 'vue';
  import { evalFormual } from '@/utils/evalFormual';
  import { onLoad } from '@dcloudio/uni-app';
  import { FieldInputAlign } from '@/enums/formEnum';
  import { UserPickerModel } from '@/services/model/formModel';
  import { getUserTree } from '@/services/api/user';
  import { ResultEnum } from '@/enums/httpEnum';
  import { Toast } from '@/utils/uniapi/prompt';

  const emits = defineEmits(['update:value', 'labelShow']);

  const props = defineProps({
    value: {
      type: Array<UserPickerModel>,
      default: () => [],
    },
    required: {
      type: Boolean,
      default: false,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    //隐藏组件的公共属性
    formula: {
      type: Object,
      default: () => {
        return {
          showFormula: '', //回显用，因为包含表单字段的时候会出现表单名称
          calcFormula: '', //解析用，表单名称对应为formData.fieldxxxx
        };
      },
    },
    formItem: {
      type: Object,
      default: () => {},
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    rule: {
      type: Object,
      default: () => null,
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    enableScan: {
      type: Boolean,
      default: false,
    },
    hidden: {
      type: Boolean,
      default: false,
    },
  });

  // field显示的值
  const valueText = ref<string>('');

  // 是否显示下拉选
  const showPicker = ref<boolean>(false);

  // 导航数据
  const navData = ref<UserPickerModel[]>([]);

  // 用户数据
  const userData = ref<UserPickerModel[]>([]);

  // 部门数据
  const deptData = ref<UserPickerModel[]>([]);

  // 是否多选, 默认单选
  const multiple = ref<boolean>(false);

  // 用户value
  const _value = ref<UserPickerModel[]>([]);

  // 选择的value,用于组件展示
  const _id_value = ref<string[]>([]);

  /** 校验规则 */
  const rules = computed(() => {
    if (isEmpty(props.rule)) {
      return [];
    } else {
      return props.rule;
    }
  });

  const doFormula = () => {
    let hidden = evalFormual(props.formula.calcFormula, props.formData);
    //如果隐藏，同时也隐藏label,通知父组件去隐藏，因为label不在当前界面
    //调用父组件FormDesignRender 的方法：
    emits('labelShow', props.formItem, hidden);
  };

  /**
   * 确认选择
   */
  const onConfirm = () => {
    if (props.required && isEmpty(_value.value)) {
      Toast('请至少选择一个' + props.formItem?.title);
      return false;
    }
    emits('update:value', _value.value);
    showPicker.value = false;
  };

  const clickItem = (userItem: UserPickerModel) => {
    // 如果单选
    if (!multiple.value) {
      if (_id_value.value.length > 0) {
        _value.value = [userItem];
        // 控制单选
        if (userItem.id !== _id_value.value[0]) {
          _id_value.value = [userItem.id];
        }
      } else {
        _value.value = [];
      }
    } else {
      // 如果存在
      if (_id_value.value.indexOf(userItem.id) !== -1) {
        _value.value.push(userItem);
      } else {
        for (let i = 0; i < _value.value.length; i++) {
          if (_value.value[i].id === userItem.id) {
            _value.value.splice(i, 1);
          }
        }
      }
    }
  };

  /**
   * 查询部门及人员数据
   * @param deptItem 部门对象
   */
  const getUserData = (deptItem: UserPickerModel) => {
    userData.value = [];
    deptData.value = [];
    getUserTree(deptItem.id).then(({ data }) => {
      if (data.code == ResultEnum.SUCCESS) {
        let dataList = data.data;
        for (let i = 0; i < dataList.length; i++) {
          let item = dataList[i];
          if (isNotBlank(item.id)) {
            if (item?.type === 'user') {
              userData.value.push(item);
            } else if (item.type === 'dept') {
              deptData.value.push(item);
            }
          }
          if (!isNotBlank(deptItem.id)) {
            nextGrade(dataList[0]);
          }
        }
      } else {
        Toast(data.msg);
      }
    });
  };

  /**
   * 下一级
   * @param deptItem 部门对象
   */
  const nextGrade = (deptItem: UserPickerModel) => {
    navData.value.push(deptItem);
    getUserData(deptItem);
  };

  /**
   * 点击导航
   * @param deptItem 部门对象
   * @param index 导航索引
   */
  const pop = (deptItem: UserPickerModel, index: number) => {
    navData.value = navData.value.slice(0, index + 1);
    getUserData(deptItem);
  };

  watch(
    () => props.formData,
    (newVal, oldVal) => {
      doFormula();
    },
    { immediate: true, deep: true },
  );

  onLoad(() => {
    multiple.value = props.formItem.props.multiple;
    _value.value = props.value;
    if (!isEmpty(props.value)) {
      _id_value.value = props.value.map((m: any) => {
        return m.id;
      });
    }
    let rootUserModel: UserPickerModel = { id: '', name: '' };
    getUserData(rootUserModel);
  });
</script>
<style scoped lang="scss">
  .user-data-container {
    background-color: #f8f8f8;
  }
  .card {
    width: 100%;
    margin-top: 20rpx;
  }

  .cell-icon {
    height: 100%;
    line-height: 1;
  }

  .suffix-icon {
    color: #1989fa;
    scale: (1.1);
  }

  .suffix-text {
    color: #1989fa;
  }

  .nav-container {
    height: 35px;
    padding-left: 10px;
    font-size: 18px;
    display: flex;
    align-items: center;
  }

  .interval {
    padding: 0px 3px;
    color: #959292;
  }

  .nav-name {
    color: #1989fa;
  }

  .ph {
    font-size: 24rpx;
    color: #c8c9cc;
  }
</style>
